package com.acooly.module.openapi.client.provider.yuejb.marshal;

import com.acooly.module.openapi.client.api.marshal.ApiMarshal;
import com.acooly.module.openapi.client.provider.yuejb.OpenAPIClientYueJBProperties;
import com.acooly.module.openapi.client.provider.yuejb.YueJBConstants;
import com.acooly.module.openapi.client.provider.yuejb.domain.YueJBRequest;
import com.acooly.module.openapi.client.provider.yuejb.utils.DomainObject2Map;
import com.acooly.module.openapi.client.provider.yuejb.utils.SignUtils;
import com.acooly.module.safety.Safes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by ouwen@yiji.com} on 2017/11/7.
 */
@Slf4j
@Service
public class YueJBRequestMarshal extends YueJBMarshallSupport implements ApiMarshal<String, YueJBRequest> {

    @Autowired
    private OpenAPIClientYueJBProperties openAPIClientYueJBProperties;

    @Override
    public String marshal(YueJBRequest source) {
        log.info("请求报文处理开始" + source.getMerchOrderNo());
        Map<String, String> requestData = doMarshal(source);
        String marshal = SignUtils.buildMapToString(requestData);
        log.info("请求报文处理结束" + marshal);
        return marshal;
    }

    /**
     * 转换待签名
     *
     * @param source
     * @return
     */
    private Map<String, String> doMarshal(YueJBRequest source) {
        Map<String, String> requestData;
        try {
            requestData = DomainObject2Map.tomap(source);
            //签名
            String waitingForSign = SignUtils.buildWaitingForSign(requestData);
            log.debug("代签名字符串:{}", waitingForSign);
            String signature = Safes.getSigner(YueJBConstants.SIGN_TYPE).sign(waitingForSign, openAPIClientYueJBProperties.getSign());
            requestData.put("sign", signature);
        } catch (Exception e) {
            log.error("请求报文处理异常：" + e.getMessage());
            return null;
        }
        return requestData;
    }
}
